/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package br.jm.acionista.filter;

import br.jm.acionista.entity.Usuario;
import java.io.IOException;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {

    private static final long serialVersionUID = 1L;
    private static final Logger LOG = Logger.getLogger(CharacterEncodingFilter.class.getName());
    private static final String loginPage = "http://localhost:8080/acionista/";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {

            Usuario usuario = getUsuarioLogado((HttpServletRequest) request);

            if (usuario == null) {

                checkLogin((HttpServletRequest) request, (HttpServletResponse) response);
            }

        } else {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
        }

        chain.doFilter(request, response);
    }

    private Usuario getUsuarioLogado(HttpServletRequest request) {
        return (Usuario) request.getSession().getAttribute("usuarioAutenticado");
    }

    private void checkLogin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {

        if (!isLoginPage(httpServletRequest.getRequestURL().toString())) {
            redirectTo(httpServletRequest, httpServletResponse, Constantes.PAGINA_LOGIN);
        }
    }

    private boolean isLoginPage(String currentPage) {
        boolean lReturn = true;
        if (!currentPage.contains("javax")) {
            if (currentPage.contains(".jsf")) {
                lReturn = currentPage.contains(Constantes.PAGINA_LOGIN);
            }
        }
        return lReturn;
    }

    private void redirectTo(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String telaSufix) throws IOException, ServletException {
        //  String url = httpServletRequest.getContextPath().concat(telaSufix);
        //  httpServletResponse.sendRedirect(loginPage);
//        FacesContext.getCurrentInstance().getExternalContext().redirect("index.jsf");

        //String novaURL = httpServletResponse.encodeRedirectURL(telaSufix);
        // httpServletResponse.sendRedirect(novaURL);

        if (!httpServletResponse.isCommitted()) {
            RequestDispatcher dispatcher = httpServletRequest.getRequestDispatcher(telaSufix);
            dispatcher.forward(httpServletRequest, httpServletResponse);
        }
    }
    /*
     * private void validateRequest(Usuario usuario, HttpServletRequest req,
     * HttpServletResponse resp) throws IOException {
     *
     * telasPermitidas = telaBusiness.getTelasPodeAcessar(usuario);
     *
     * boolean podeAcessar = podeAcessarTela(usuario,
     * req.getRequestURL().toString()); Integer flagControle =
     * isControle(usuario, req.getRequestURL().toString(), req.getRemoteAddr());
     *
     * req.getSession().setAttribute(IP_SESSION_KEY, req.getRemoteAddr());
     *
     * if (podeAcessar && flagControle != CONTR_ALLOW) { String err = "O usuário
     * " + configuracaoBusiness.getUserInControle().getStrLogin() + " está
     * utilizando o Controle!"; LOG.severe(err); redirectTo(req, resp,
     * TELA_HOME_SUFIX + "?controleError=" + flagControle.toString()); } else if
     * (!podeAcessar || isSessionInvalid(req)) { LOG.severe("Usuario sem
     * permissao para acessar a seguinte tela: " +
     * req.getRequestURL().toString()); redirectTo(req, resp, TELA_HOME_SUFIX);
     * } }
     *
     */

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}